<?php
namespace app\controllers;

use app\logic\UserLogic;
use yii;

class UserController extends BackendController
{


    public function actionIndex()
    {
        $query = Yii::$app->request->get('form', []);
        $page = Yii::$app->request->get('page', 1);
        $useLogic = new UserLogic();
        $this->data['breadcrumbs'] = '用户管理';
        if(!isset($query['phone']))
            $query['phone'] = '';
        return $this->render('index', [
            'phone'=>$query['phone'],
            'user' => $useLogic->getUser($query, $page),
            'query' => $query
        ]);
    }

    public function actionAdd()
    {
        if(!Yii::$app->request->post()){
            $this->data['breadcrumbs'] = ['用户管理' => U('user/index'), ' 添加用户' => ''];
            return $this->render('add', [
                'actionUrl' => U('user/add')
            ]);
        }else{
            $params = Yii::$app->request->post('form');
            $userLogic = new UserLogic();
            $logicRes = $userLogic->addUser($params);
            if ($logicRes) {
                Yii::$app->getSession()->setFlash('success','新增用户成功');
                jump('user/index');
            } else {
                Yii::$app->getSession()->setFlash('error','新增用户失败');
                $this->goBack(Yii::$app->request->referrer);
            }
        }
    }

    public function actionEdit()
    {
        $userLogic = new UserLogic();
        if(!Yii::$app->request->post()){
            $this->data['breadcrumbs'] = ['用户管理' => U('user/index'), ' 编辑用户' => ''];
            $id = Yii::$app->request->get('user_id');
            $user = $userLogic->getById($id);
            return $this->render('edit', [
                'user'=>$user,
                'actionUrl' => U('user/edit')
            ]);
        }else{
            $params = Yii::$app->request->post('form');
            $id = Yii::$app->request->post('user_id');
            $logicRes = $userLogic->editUserById($id,$params);
            if ($logicRes['result']) {
                Yii::$app->getSession()->setFlash('success','编辑用户成功');
                jump('user/index');
            } else {
                Yii::$app->getSession()->setFlash('error',$logicRes['msg']);
                $this->goBack(Yii::$app->request->referrer);
            }
        }
    }

    public function actionSaveStatus()
    {
        $id = Yii::$app->request->get('user_id');
        $userLogic = new UserLogic();
        $logicRes = $userLogic->saveStatus($id);
        if ($logicRes) {
            Yii::$app->getSession()->setFlash('success','更改用户状态成功');
        } else {
            Yii::$app->getSession()->setFlash('error','更改用户状态失败');
        }
        return $this->redirect(U('user/index'));
    }





}